﻿$.MGJ.RPActivity = [];
(function () {
    var _this = $.MGJ.RPActivity;
    $.extend($.MGJ.RPActivity, {
        //红包保存
        Ajax_Save: function () {
            sessionStorage.removeItem('alertSave');
            sessionStorage.removeItem('isFirst');
            sessionStorage.removeItem('isLeave');


            //$("#finalSave").attr("disabled", true);
            $('.clickEdict').css('display', 'none');
            $('.ui-resizable-handle').remove();
            var b = new this.Base64();
            var template = {
                ID: $("#TemId").val(),
                ActivityHome: b.encode($("#red1").html()),//首页
                ActivityRuleState: b.encode($("#red2 .bg-con").html()),//活动说明规则 
                MyPrizeRecord: b.encode($("#red3").html()),//中奖记录
                PrizeDetailsShow: b.encode($("#red4").html()),//奖品明细 
                Verification: b.encode($("#red5").html()),//手机验证
                GetSucceed: b.encode($("#red6 .bg-con").html()),//中奖页面
                GetError: b.encode($("#red7 .bg-con").html()),//没中奖页面
                GetYet: b.encode($("#red8 .bg-con").html()),//奖品被领取
                GetInForm: b.encode($("#red9").html()),//奖品领取完成
                NotStart: b.encode($("#red10").html()),//活动未开始
            }
            var activity_form = $("#activity_form").serializeObject();
            if ($("#IsLimitArea").val() == 1)
            {
                activity_form["Privance"] = $("#Privance").val() == null ?" " : $("#Privance").val().join(",");
                activity_form["City"] = $("#City").val() == null ? " " : $("#City").val().join(",");
            }
            var delivery_form = $("#delivery_form").serializeObject();
            var Awardform01 = $("#Award01").serializeObject();
            var activityInfo_form = $("#activityInfo_form").serializeObject();
            var AwardsData = [];
            AwardsData.push(Awardform01);
            var data = JSON.stringify({
                template: template,
                activity: activity_form,
                delivery: delivery_form,
                awardsList: AwardsData,
                webInfo: activityInfo_form,
            });
            var batchInput = $("#batchInput").val();
            if (batchInput == "@Model.activity.Batch") {
                $.L.msgError("请填写生码批次！");
            }
            else {
                if ($(event.target).attr("id") != "batch") {
                    $.ajax({
                        url: ACTION_URL("ActivityAdd", "Market"),
                        contentType: "application/json",
                        type: "POST",
                        datatype: "json",
                        data: data,
                        success: function (data) {
                            if (data == true) {
                                $.MGJ.Common.loadurl(this, '/Market/ActivitiesManage');
                                $.L.msgSuccess('保存成功！');
                            }
                            else {
                                $.L.msgError("保存失败，可能原因：" + data);
                                $("#finalSave").attr("disabled", false);
                            }
                        }
                    })
                }
                else {
                    return
                }
            }
        },
        //编辑页面时初始化
        Ajax_Initialization: function (obj) {
            $("#red1").html("");
            $("#red2  .bg-con").html("");
            $("#red3").html("");
            $("#red4").html("");
            $("#red5").html("");
            $("#red6  .bg-con").html("");
            $("#red7  .bg-con").html("");
            $("#red8  .bg-con").html("");
            var b = new this.Base64();
            $.L.ajaxHandle({
                url: ACTION_URL("GetTemplate", "Market") + "?aId=" + obj,
                success: function (response) {
                    if (response) {
                        $("#TemId").val(response.ID);
                        $("#red1").html(b.decode(response.ActivityHome));
                        $("#red2  .bg-con").html(b.decode(response.ActivityRuleState));
                        $("#red3").html(b.decode(response.MyPrizeRecord));
                        $("#red4").html(b.decode(response.PrizeDetailsShow));
                        $("#red5").html(b.decode(response.Verification));
                        $("#red6  .bg-con").html(b.decode(response.GetSucceed));
                        $("#red7  .bg-con").html(b.decode(response.GetError));
                        $("#red8  .bg-con").html(b.decode(response.GetYet));
                    }
                    $('.clickEdict').removeAttr('style');
                    //可拖可拽
                    $('.resizable.draggable').resizable({
                        containment: 'parent',
                        stop: function (e,ui) {
                            var parentW = $(this).parent().width();
                            var parentH = $(this).parent().height();
                            var _thisW = $(this).width();
                            var _thisH = $(this).height();
                            var left = parseInt($(this).css('left'));
                            var top = parseInt($(this).css('top'));
                            $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
                        }
                    });
                    $('.resizable.draggable').draggable({
                        containment: 'parent',
                        stop: function () {
                            var parentW = $(this).parent().width();
                            var parentH = $(this).parent().height();
                            var _thisW = $(this).width();
                            var _thisH = $(this).height();
                            var left = parseInt($(this).css('left'));
                            var top = parseInt($(this).css('top'));
                            $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
                        }
                    });
                    $('.draggable').draggable({
                        containment: 'parent',
                        stop: function () {
                            var parentW = $(this).parent().width();
                            var parentH = $(this).parent().height();
                            var _thisW = $(this).width();
                            var _thisH = $(this).height();
                            var left = parseInt($(this).css('left'));
                            var top = parseInt($(this).css('top'));
                            $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
                        }
                    });
                }
            });
        },
        Base64: function (input) {
            _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            // public method for encoding
            this.encode = function (input) {
                var output = "";
                if (input == null) return output;
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;
                input = _utf8_encode(input);
                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);
                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;
                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }
                    output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
                }
                return output;
            }
            // public method for decoding
            this.decode = function (input) {
                var output = "";
                if (input == null) return output;
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                while (i < input.length) {
                    enc1 = _keyStr.indexOf(input.charAt(i++));
                    enc2 = _keyStr.indexOf(input.charAt(i++));
                    enc3 = _keyStr.indexOf(input.charAt(i++));
                    enc4 = _keyStr.indexOf(input.charAt(i++));
                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;
                    output = output + String.fromCharCode(chr1);
                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                }
                output = _utf8_decode(output);
                return output;
            }
            // private method for UTF-8 encoding
            _utf8_encode = function (string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    } else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                }
                return utftext;
            }
            // private method for UTF-8 decoding
            _utf8_decode = function (utftext) {
                var string = "";
                var i = 0;
                var c = c1 = c2 = 0;
                while (i < utftext.length) {
                    c = utftext.charCodeAt(i);
                    if (c < 128) {
                        string += String.fromCharCode(c);
                        i++;
                    } else if ((c > 191) && (c < 224)) {
                        c2 = utftext.charCodeAt(i + 1);
                        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                        i += 2;
                    } else {
                        c2 = utftext.charCodeAt(i + 1);
                        c3 = utftext.charCodeAt(i + 2);
                        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                        i += 3;
                    }
                }
                return string;
            }
        },
        GetAwardNum: function (index) {
            var id = "#JackpotID" + index;
            var idNum = "#JackepotNum" + index;
            $(idNum).text($(id + " option:selected").data("num"));
            if ($(idNum).text() == "0") {
                $("#TotalNums" + index).val(0);
                $("#Rate" + index).val(0);
            }
        },
        GetAward: function (type, index, boxVal, oper) {
            
            boxVal = boxVal || 0;
            var id = "#JackpotID" + index;
            $(id).html("");
            var idNum = "#JackepotNum" + index;
            $(idNum).html("");
            $.ajax({
                type: "post",
                url: '/Market/JackpotBox',
                data: { type: type },
                success: function (data) {
                    var $option = "";
                    if (data.length > 0) {
                        $option += "<option value='0' data-num='0'    >---请选择---</option>";
                        for (var i = 0; i < data.length; i++) {
                            if (boxVal != 0 && boxVal == data[i].Id) {
                                $option += "<option value='" + data[i].Id + "' data-num='" + data[i].ResidueNums + "' selected    >" + data[i].Name + "</option>";
                                $(idNum).text(data[i].ResidueNums).css('color', '#43A63A');
                                boxValArr.push(boxVal);
                            }
                            else {
                                //判断奖项是否被用过
                                var b = true;
                                for (var j = 0; j < boxValArr.length; j++) {
                                    if (boxValArr[j] == data[i].Id) {
                                        b = false;
                                        break;
                                    }
                                }
                                if (b) {
                                    if (oper == "add" && i == 0) {
                                        $option += "<option value='" + data[i].Id + "' data-num='" + data[i].ResidueNums + "'  selected='selected'   >" + data[i].Name + "</option>";

                                    }
                                    else
                                        $option += "<option value='" + data[i].Id + "' data-num='" + data[i].ResidueNums + "'    >" + data[i].Name + "</option>";
                                }

                            }
                        }
                    }
                    else {
                        $option += "<option value='0' data-num='0'    >---暂无数据---</option>";
                    }
                    $(id).html($option);
                    $.MGJ.RPActivity.GetAwardNum(index);
                }
            });
        },
        changeJackpotType: function (ele, index) {
            var type = $(ele).val();
            $.MGJ.RPActivity.GetAward(type, index);
            if (type == 1) {
                $('#AwName').text('微信红包2元');
            }
            else if (type == 2) {
                $('#AwName').text('10元天猫优惠券')
            }
            else if (type == 3) {
                $('#AwName').text('2元流量券')
            }
        }
    })
})(jQuery);


(function ($) {
    $.fn.extend({
        serializeObject: function () {
            if (this.length > 1) {
                return false;
            }
            var arr = this.serializeArray();
            var obj = new Object;
            $.each(arr, function (k, v) {
                obj[v.name] = v.value;
            });
            return obj;
        }
    });
})(jQuery);
